package com.dayatang.product.domain;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;

import com.dayatang.domain.QuerySettings;


@Entity
@Table(name = "send_mails")
public class SendMail extends MyAbstractEntity {

	private static final long serialVersionUID = 9095115731789884775L;

	@ManyToOne
	@JoinColumn(name = "html_mail_id")
	private HtmlMail htmlMail;
	
	@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "sendMail", fetch=FetchType.EAGER)
	private Set<MailReceiver> mailReceivers = new HashSet<MailReceiver>();
	
	@Column(name = "is_send")
	private boolean isSend = false;
	
	public HtmlMail getHtmlMail() {
		return htmlMail;
	}

	public void setHtmlMail(HtmlMail htmlMail) {
		this.htmlMail = htmlMail;
	}

	public Set<MailReceiver> getMailReceivers() {
		return new HashSet<MailReceiver>(mailReceivers);
	}

	public void addMailReceiver(MailReceiver mailReceiver) {
		mailReceiver.setSendMail(this);
		mailReceivers.add(mailReceiver);
	}
	
	public void removeMailReceiver(MailReceiver mailReceiver) {
		mailReceivers.remove(mailReceiver);
	}

	public boolean getIsSend() {
		return isSend;
	}

	public void setSend(boolean isSend) {
		this.isSend = isSend;
	}

	public static SendMail getSendMailByAbstractMail(HtmlMail htmlMail) {
		List<SendMail> sendMails = getRepository().find(QuerySettings.create(SendMail.class).eq("htmlMail", htmlMail));
		return sendMails.get(sendMails.size()-1);
	}
	
	public boolean equals(final Object other) {
		if (this == other)
			return true;
		if (!(other instanceof SendMail))
			return false;
		SendMail castOther = (SendMail) other;
		return new EqualsBuilder().append(htmlMail, castOther.htmlMail).isEquals();
	}

	public int hashCode() {
		return new HashCodeBuilder(17, 37).append(htmlMail).toHashCode();
	}

	public String toString() {
		return htmlMail.toString();
	}

}
